import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DatabaseInitializer {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useSSL=false";
        String username = "root";
        String password = "root";
        
        try {
            // 加载MySQL驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            // 连接数据库
            System.out.println("正在连接MySQL数据库...");
            Connection conn = DriverManager.getConnection(url, username, password);
            System.out.println("连接成功！");
            
            // 读取SQL文件
            String sqlContent = new String(Files.readAllBytes(Paths.get("init-database.sql")));
            
            // 分割SQL语句（按分号分割）
            String[] sqlStatements = sqlContent.split(";");
            
            Statement stmt = conn.createStatement();
            
            // 执行每条SQL语句
            for (String sql : sqlStatements) {
                sql = sql.trim();
                if (!sql.isEmpty() && !sql.startsWith("--")) {
                    try {
                        System.out.println("执行: " + sql.substring(0, Math.min(50, sql.length())) + "...");
                        stmt.execute(sql);
                    } catch (Exception e) {
                        System.err.println("执行失败: " + e.getMessage());
                    }
                }
            }
            
            System.out.println("\n数据库初始化完成！");
            
            stmt.close();
            conn.close();
            
        } catch (Exception e) {
            System.err.println("错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
